<template>
    <view class="page" :class="{ 'dark-mode': isDarkMode }">
        <!-- 状态栏占位 -->
        <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

        <!-- 标题栏 -->
        <view class="title-bar">
            <text class="page-title">分享给我的礼簿</text>
        </view>

        <!-- 搜索框 -->
        <view class="search-wrapper">
            <view class="search-bar">
                <text class="search-icon bigfont big-sousuo"></text>
                <input type="text" placeholder="搜索分享记录"
                    :placeholder-style="'color:' + (isDarkMode ? 'rgba(255, 255, 255, 0.6)' : '#999')"
                    class="search-input" v-model="searchText" @input="handleSearch" />
                <text v-if="searchText" class="clear-icon bigfont big-guanbi" @tap="clearSearch"></text>
            </view>
        </view>

        <!-- 分享列表 -->
        <scroll-view class="share-list" scroll-y @scrolltolower="loadMore" @refresherrefresh="onRefresh"
            :refresher-enabled="true" :refresher-triggered="isRefreshing" refresher-background="transparent">

            <view v-if="loading && !isRefreshing && shareList.length === 0" class="list-status">
                <text class="status-text">加载中...</text>
            </view>

            <view v-else-if="shareList.length === 0" class="list-status empty-status">
                <view class="empty-icon">📝</view>
                <text class="empty-text">暂无分享记录</text>
            </view>

            <view v-else class="share-list-content">
                <view class="share-item" v-for="(item, index) in shareList" :key="index">
                    <view class="book-main">
                        <view class="book-cover">
                            <image :src="item.books?.coverImageUrl" mode="aspectFill"></image>
                        </view>
                        <view class="book-info">
                            <text class="book-title">{{ item.books?.title || '未知礼簿' }}</text>
                            <view class="book-meta">
                                <text class="book-date">{{ formatDate(item.createTime) }}</text>
                                <text class="type-tag" :class="{ 'readonly': item.type === 'readonly' }">
                                    {{ item.type === 'readonly' ? '只读' : '可编辑' }}
                                </text>
                                <view class="quit-btn" @tap.stop="handleQuitBook(item)">
                                    <text class="bigfont big-shanchu quit-icon"></text>
                                    <text>退出</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 加载更多状态 -->
                <view v-if="loading && shareList.length > 0" class="load-more loading">
                    <view class="loading-indicator"></view>
                    <text class="load-more-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="load-more">
                    <text class="load-more-text">没有更多了</text>
                </view>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { cancelShareReceive, listShareMyGiftBooks, type ShareRecord } from '@/api/share-receive';
import { isDarkMode } from '@/store/theme';
import { onMounted, ref, watch } from 'vue';

interface ApiResponse<T = any> {
    code: number;
    msg: string;
    data: {
        records: T[];
        pageNumber: number;
        pageSize: number;
        totalPage: number;
        totalRow: number;
    };
}

type FormattedShareRecord = ShareRecord & {
    type: string;
}

// 状态栏高度
const statusBarHeight = ref(0);

// 分享列表数据
const shareList = ref<FormattedShareRecord[]>([]);
const loading = ref(false);
const isRefreshing = ref(false);
const hasMore = ref(true);
const searchText = ref('');

const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    searchValue: ''
});

// 搜索处理
const handleSearch = () => {
    queryParams.value.searchValue = searchText.value;
    getList(true);
};

// 清除搜索
const clearSearch = () => {
    searchText.value = '';
    queryParams.value.searchValue = '';
    getList(true);
};

// 加载更多
const loadMore = () => {
    getList();
};

// 下拉刷新
const onRefresh = () => {
    isRefreshing.value = true;
    getList(true);
};

// 格式化日期
const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取分享列表
const getList = async (reset = false) => {
    if (reset) {
        queryParams.value.pageNum = 1;
        shareList.value = [];
        hasMore.value = true;
    }

    if (!hasMore.value || loading.value) return;

    loading.value = true;
    try {
        const response = await listShareMyGiftBooks(queryParams.value);
        const result = response as unknown as ApiResponse<ShareRecord>;
        const { records = [], totalRow = 0 } = result.data || {};

        const formattedRecords = records.map(item => ({
            ...item,
            type: item.books?.type || 'readonly'
        }));

        if (reset) {
            shareList.value = formattedRecords;
        } else {
            shareList.value = [...shareList.value, ...formattedRecords];
        }

        hasMore.value = shareList.value.length < totalRow;
        queryParams.value.pageNum++;
    } catch (error) {
        console.error('获取分享列表失败:', error);
        uni.showToast({
            title: '获取数据失败',
            icon: 'error'
        });
    } finally {
        loading.value = false;
        isRefreshing.value = false;
    }
};

// 更新导航栏颜色
const updateNavBarStyle = () => {
    uni.setNavigationBarColor({
        frontColor: isDarkMode.value ? '#ffffff' : '#000000',
        backgroundColor: isDarkMode.value ? '#121212' : '#ffffff'
    });
};

// 监听主题变化
watch(isDarkMode, () => {
    updateNavBarStyle();
});

// 退出处理
const handleExit = () => {
    uni.navigateBack();
};

// 退出礼簿
const handleQuitBook = (item: FormattedShareRecord) => {
    uni.showModal({
        title: '提示',
        content: '确定要退出该礼簿吗？',
        success: async (res) => {
            if (res.confirm) {
                try {
                    const response = await cancelShareReceive(item.id);
                    const result = response as unknown as ApiResponse<any>;
                    if (result.code === 200) {
                        uni.showToast({
                            title: '退出成功',
                            icon: 'success'
                        });
                        // 刷新列表
                        getList(true);
                    } else {
                        uni.showToast({
                            title: result.msg || '退出失败',
                            icon: 'error'
                        });
                    }
                } catch (error) {
                    console.error('退出礼簿失败:', error);
                    uni.showToast({
                        title: '退出失败',
                        icon: 'error'
                    });
                }
            }
        }
    });
};

// 页面加载
onMounted(() => {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;

    // 设置导航栏颜色
    updateNavBarStyle();

    // 获取列表数据
    getList(true);
});
</script>

<style scoped>
.page {
    min-height: 100vh;
    background-color: var(--theme-background);
    padding-bottom: env(safe-area-inset-bottom);
    display: flex;
    flex-direction: column;
    touch-action: none;
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
}

.status-bar {
    width: 100%;
    background-color: transparent;
    flex-shrink: 0;
}

.title-bar {
    padding: 20rpx 32rpx;
    flex-shrink: 0;
}

.page-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    line-height: 1.4;
}

.dark-mode .page-title {
    color: #fff;
}

.search-wrapper {
    padding: 20rpx 32rpx;
    background-color: transparent;
    flex-shrink: 0;
}

.search-bar {
    display: flex;
    align-items: center;
    padding: 0 24rpx;
    height: 80rpx;
    border-radius: 40rpx;
    background: #ffffff;
    border: 2rpx solid #e8e8e8;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
    transition: all 0.3s ease;
}

.dark-mode {
    background-color: #121212;
}

.dark-mode .search-bar {
    background: #1e1e1e;
    border-color: rgba(255, 255, 255, 0.1);
}

.search-bar:focus-within {
    border-color: rgba(76, 175, 80, 0.5);
    box-shadow: 0 2rpx 12rpx rgba(76, 175, 80, 0.1);
    background: #ffffff;
}

.dark-mode .search-bar:focus-within {
    background: #1e1e1e;
    border-color: rgba(76, 175, 80, 0.5);
    box-shadow: 0 2rpx 12rpx rgba(76, 175, 80, 0.1);
}

.search-icon {
    font-size: 36rpx;
    color: #999;
    margin-right: 12rpx;
}

.search-input {
    flex: 1;
    height: 100%;
    font-size: 28rpx;
    color: #333;
    background: transparent;
}

.dark-mode .search-input {
    color: rgba(255, 255, 255, 0.9);
}

.clear-icon {
    font-size: 32rpx;
    color: #999;
    padding: 12rpx;
}

.share-list {
    flex: 1;
    height: 0;
    box-sizing: border-box;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
}

.list-status {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
}

.status-text {
    font-size: 28rpx;
    color: #999;
}

.empty-status {
    text-align: center;
}

.empty-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
}

.empty-text {
    font-size: 28rpx;
    color: #999;
}

.share-list-content {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
    padding: 32rpx;
}

.share-item {
    background: #ffffff;
    border-radius: 12rpx;
    padding: 16rpx;
    display: flex;
    flex-direction: column;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    width: 100%;
    box-sizing: border-box;
    position: relative;
    will-change: background-color, border-color;
    margin-bottom: 16rpx;
}

.dark-mode .share-item {
    background: #1e1e1e;
    border: 2rpx solid rgba(255, 255, 255, 0.1);
}

.book-main {
    display: flex;
    gap: 24rpx;
    align-items: flex-start;
    cursor: pointer;
}

.book-main:active {
    opacity: 0.8;
}

.book-cover {
    width: 100rpx;
    height: 100rpx;
    border-radius: 8rpx;
    overflow: hidden;
    flex-shrink: 0;
    margin-right: 16rpx;
}

.book-cover image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.book-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    min-width: 0;
}

.book-title {
    font-size: 30rpx;
    color: #333;
    font-weight: 500;
    margin-bottom: 8rpx;
    line-height: 1.3;
}

.dark-mode .book-title {
    color: rgba(255, 255, 255, 0.9);
}

.book-meta {
    display: flex;
    align-items: center;
    gap: 16rpx;
}

.book-date {
    font-size: 24rpx;
    color: #999;
}

.type-tag {
    font-size: 24rpx;
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    background-color: #e6f7ff;
    color: #1890ff;
    display: flex;
    align-items: center;
    justify-content: center;
}

.type-tag.readonly {
    background-color: #f5f5f5;
    color: #999;
}

.dark-mode .type-tag {
    background-color: rgba(24, 144, 255, 0.1);
}

.dark-mode .type-tag.readonly {
    background-color: rgba(255, 255, 255, 0.1);
    color: rgba(255, 255, 255, 0.6);
}

.load-more {
    text-align: center;
    padding: 32rpx 0;
}

.loading {
    display: flex;
    align-items: center;
    justify-content: center;
}

.loading-indicator {
    width: 32rpx;
    height: 32rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #3498db;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 12rpx;
}

.load-more-text {
    font-size: 24rpx;
    color: #999;
}

.dark-mode .load-more-text {
    color: rgba(255, 255, 255, 0.6);
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

.exit-btn {
    padding: 12rpx 24rpx;
    border-radius: 8rpx;
    background-color: #f5f5f5;
}

.dark-mode .exit-btn {
    background-color: #2c2c2c;
}

.exit-text {
    font-size: 28rpx;
    color: #666;
}

.dark-mode .exit-text {
    color: rgba(255, 255, 255, 0.8);
}

.quit-btn {
    margin-left: auto;
    padding: 4rpx 16rpx;
    border-radius: 4rpx;
    background-color: rgba(255, 77, 79, 0.1);
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4rpx;
}

.quit-btn .quit-icon {
    font-size: 24rpx;
    color: #ff4d4f;
}

.quit-btn text {
    font-size: 24rpx;
    color: #ff4d4f;
    font-weight: 500;
}

.dark-mode .quit-btn {
    background-color: rgba(255, 77, 79, 0.15);
}

.dark-mode .quit-btn text,
.dark-mode .quit-btn .quit-icon {
    color: #ff7875;
}

.quit-btn:active {
    opacity: 0.7;
}
</style>